<template>
	<view class="comerciante-container" :style="{ height: introductionVisible ? '100vh' : '100%', overflow: introductionVisible ? 'hidden' : 'visible' }">
		<!-- 顶部导航栏 -->
		<view class="header">
			<x-status-bar></x-status-bar>
			<view class="flex-center-between header-navbar">
				<x-back-btn></x-back-btn>
				<view class="u-f-40 font-bold common-title">{{ lang_comerciante.detailTitle }}</view>
				<view class="u-f-32" @click="(menuVisible = true) && (introductionVisible = false)">
					<u-icon name="more-dot-fill" size="36"></u-icon>
				</view>
			</view>
		</view>

		<!-- 橱窗图 -->
		<view class="top-img-container u-text-center u-m-t-10">
			<view class="top-img" style="margin: 0 auto">
				<u-swiper :list="shopImages" height="352" mode="none"></u-swiper>
			</view>
		</view>

		<!-- 概览 -->
		<view class="u-p-30">
			<view class="flex-between">
				<view class="u-f-44 font-bold u-lh-60">{{ dataInfo.name || '' }}</view>

				<!-- 收藏状态 -->
				<view :class="['collect-btn u-f-24 u-text-center font-medio', collect ? 'collect-btn-active' : '']"
					@click="changeCollectAction">{{ lang_common[(collect ? 'un' : '') + 'collect'] }}</view>
			</view>

			<!-- 评分器 -->
			<view class="flex u-m-t-16">
				<view class="u-m-r-16 font-medio u-lh-40">{{ dataInfo.categoryTitle || '' }}</view>
				<x-rate :value="shopScore || 5 "></x-rate>
			</view>

			<!-- 地址信息 -->
			<view class="flex-center-between u-m-t-18">
				<view class="linecamp-2">{{ formatAddress(dataInfo, 1) }}</view>

				<view class="clear-flex flex-center ">
					<view class="u-text-center u-m-l-26" @click="navAction()">
						<image src="@/static/image/common/go.png" style="width: 34rpx; height: 32rpx;"></image>
						<view class="u-m-t-12">{{ lang_common.here }}</view>
					</view>
					<view class="u-text-center u-m-l-26" @click="changeCallAction">
						<image src="@/static/image/common/call.png" style="width: 32rpx; height: 32rpx;"></image>
						<view class="u-m-t-12">{{ lang_common.call }}</view>
					</view>
				</view>
			</view>

			<!-- 预约按钮 -->
			<view style="width: 100%; padding: 0 8rpx" class="u-m-t-38 flex-center-center">
				<x-common-btn width="676" boxShadow="0 4rpx 8rpx 0 rgba(252, 31, 63, 0.31)" @click="changeNav(1)" :disabled="!serviceList.length">
					{{ lang_common.subscribe_now }}
				</x-common-btn>
			</view>
		</view>

		<!-- 分割线 -->
		<u-gap height="4" bgColor="#f7f7f7"></u-gap>

		<!-- 简介 -->
		<view class="flex" style="padding: 30rpx 24rpx 36rpx 40rpx" @click="introductionVisible = true">
			<view class="detail-img u-m-r-20 clear-flex">
				<x-image :src="showImage(dataInfo.logoImgUrl, 'logo')" class="auto-img" />
			</view>

			<view class="flex-between flex-column">
				<view class="u-f-32 u-lh-44">{{ dataInfo.name || '' }}</view>

				<view class="u-f-26 u-lh-36 color-grew linecamp-2" style="width: calc(100vw - 210rpx);">
					{{ dataInfo.desc || '' }}
				</view>
			</view>
		</view>

		<!-- 分割线 -->
		<u-gap height="4" bgColor="#f7f7f7"></u-gap>

		<!-- 导航一 -->
		<view class="nav-container flex-center-between" style="padding: 16rpx 30rpx 16rpx 28rpx">
			<view v-for="(item, index) in navs" :key="index" @click="changeNav(index)">
				<view :class="['u-f-36 u-lh-50', index === navIndex ? 'nav-active font-medio' : '']">
					{{ lang_common[item.key] }}
				</view>

				<view class="u-f-24 u-lh-34 color-grew u-text-center">
					{{ dataInfo[item.dataKey] }}{{ lang_unit[item.unitKey] }}
				</view>
			</view>
		</view>

		<!-- 分割线 -->
		<u-gap height="4" bgColor="#f7f7f7"></u-gap>

		<!-- 导航数据 -->
		<view class="u-p-l-40 u-p-r-40">
			<!-- 优惠券 -->
			<view class="coupon-container">
				<view v-for="(item, index) in couponList" :key="index">
					<coupon-item :item="({ ...item, merchantName: dataInfo.name })"></coupon-item>
				</view>
			</view>
			<mescroll-empty v-if="!couponList.length && serviceList.length"></mescroll-empty>
			<!-- 服务 -->
			<view class="service-container">
				<view v-for="(item, index) in serviceList" :key="index">
					<service-item :item="item" :merchantId="dataInfo.merchantId"></service-item>
				</view>
			</view>
			<mescroll-empty v-if="!serviceList.length"></mescroll-empty>
			<!-- 探店笔记 -->
			<view class="note-container">
				<view class="u-p-t-26 u-p-b-34">
					<view class="flex-center-between">
						<view class="u-f-36 u-lh-50">{{ lang_common.shopNote }}</view>
						<x-see-more v-if="notesList.length" @click="jumpUrl(`/pages/user/shop/note/note?merchantId=${ dataInfo.merchantId }&type=discover`)">
						</x-see-more>
					</view>

					<view v-for="(item, index) in notesList" :key="index" class="note-card u-m-t-22"
						@click="jumpUrl(`/pages/other/comment/note?commentId=${ item.commentId }&notesId=${ item.notesId }`)">
						<note-item :item="item"></note-item>
					</view>
				</view>
				<mescroll-empty v-if="!notesList.length"></mescroll-empty>
			</view>

			<!-- 评价 -->
			<view class="evaluate-container">
				<view class="u-p-t-26 u-p-b-34">
					<view class="flex-center-between">
						<view class="u-f-36 u-lh-50">{{ lang_common.evaluate }}</view>
						<x-see-more
							v-if="commentList.length"
							@click="jumpUrl(`/pages/user/comerciante/comment/list?merchantId=${ dataInfo.merchantId }`)">
						</x-see-more>
					</view>

					<view v-for="(item, index) in commentList" :key="index" class="u-m-t-24">
						<evaluate-item :item="item">
							<view slot="footer" class="flex">{{ item.bodyTitle || '' }}</view>
						</evaluate-item>
					</view>
					<mescroll-empty v-if="!commentList.length"></mescroll-empty>
				</view>
			</view>
		</view>

		<!-- 留空 -->
		<view style="height: 200rpx"></view>

		<!-- 右上角遮罩层 -->
		<x-menu v-model="menuVisible" @change="menuAction"></x-menu>

		<!-- 简介弹窗 -->
		<x-introbute v-model="introductionVisible" :info="dataInfo"></x-introbute>
		
		<!-- 分享 -->
		<x-share v-model="shareVisible"></x-share>
		
		<permission-unAuthTips v-model="settingValue"></permission-unAuthTips>
	</view>
</template>

<script>
	import {
		merchantInfo
	} from '@/api/user/merchant.js'
	import XIntrobute from './components/x-introbute'
	import XMenu from './components/x-menu'
	import CouponItem from './components/coupon-item'
	import NoteItem from './components/note-item'
	import ServiceItem from './components/service-item'

	let domClass = ['.coupon-container', '.service-container', '.note-container', '.evaluate-container']
	export default {
		components: { XIntrobute, XMenu, CouponItem, NoteItem, ServiceItem },
		data() {
			
			return {
				/* 右上角导航 */
				menuVisible: false,
				shareVisible: false,

				/* 收藏状态 */
				collect: false,
				/* 商家唯一标识 */
				merchantId: '',
				dataInfo: {},

				/* 简介状态 */
				introductionVisible: false,

				/* 导航 */
				navs: [{
						label: '优惠券',
						key: 'coupon',
						unitKey: 'sheets',
						dataKey: 'couponCount'
					},
					{
						label: '服务',
						key: 'service',
						unitKey: 'ge',
						dataKey: 'serviceCount'
					},
					{
						label: '探店笔记',
						key: 'shopNote',
						unitKey: 'tiao',
						dataKey: 'notesCount'
					},
					{
						label: '评价',
						key: 'evaluate',
						unitKey: 'tiao',
						dataKey: 'commentCount'
					}
				],
				navIndex: 0,
				navClick: false,
				
				timer: null,
				
				settingValue: ''
			}
		},
		computed: {
			shopImages() {
				let str = this.dataInfo.environmentImgUrls || ''
				let list = str.split(',') || []
				return list.map(item => this.showImage(item))
			},
			couponList() {
				return this.dataInfo.couponList || []
			},
			serviceList() {
				return this.dataInfo.serviceList || []
			},
			notesList() {
				return this.dataInfo.notesList || []
			},
			commentList() {
				return this.dataInfo.commentList || []
			},
			shopScore() {
				let { totalScore, totalComments } = this.dataInfo
				return (totalScore || 0) / (totalComments || 1)
			}
		},
		onBackPress() {
			let list = ['menuVisible', 'shareVisible', 'introductionVisible']
			if (list.find(item => this[item])) {
				list.map(item => (this[item] = false))
				return true
			}
			return false
		},
		onPageScroll({
			scrollTop
		}) {
			if (this.menuVisible) {
				this.menuVisible = false
			}
			// 监听是否到达某个元素, 
			clearTimeout(this.timer)
			this.timer = setTimeout(async () => {
				if (this.navClick) {
					this.navClick = false
					clearTimeout(this.timer)
					return
				}
				let topDom = await this.query('.top-img-container')
				let navDom = await this.query('.nav-container')
				Promise.all(domClass.map(item => this.query(item))).then((result) => {
					let temp = 0
					result.map((itemDom, index) => {
						if (scrollTop > (itemDom.top - topDom.top - navDom.height)) {
							temp = index
						}
					})
					this.navIndex = temp < 0 ? 0 : temp
				})
			}, 100)
		},
		onPullDownRefresh() {
			uni.stopPullDownRefresh()
			clearTimeout(this.timer)
			this.timer = setTimeout(() => {
				this.getInfo()
				
			}, 1000)
		},
		onShow() {
			if (this.merchantId) {
				this.getInfo()
			}
		},
		onLoad({
			merchantId
		}) {
			this.merchantId = merchantId
			this.getInfo()
		},
		methods: {
			async changeCallAction() {
				let { prefixCode, phone } = this.dataInfo
				this.settingValue = await this.callAction((prefixCode || '') + phone)
			},
			// 获取元素
			// 这里的导航使用外部APP导航【apple地图、谷歌地图】
			// 维度 经度 关键字
			navAction() {
				let {
					latitude: lat,
					longitude: lng,
					name: keyword
				} = this.dataInfo
				let url = ''
				if (plus.os.name == 'Android') {
					url = `geo:${ lat },${ lng }?q=${ keyword }`
					plus.runtime.openURL(url);
				} else {
					/** 
					 * iOS上获取本机是否安装了，需要在manifest里配置，
					 * 在manifest.json文件
					 * app-plus->distribute->apple->urlschemewhitelist节点下
					 * 添加（如urlschemewhitelist:["iosamap","comgooglemaps"]）
					 * */
					plus.nativeUI.actionSheet({
						title: '选择地图应用',
						cancel: '取消',
						buttons: [{
							title: 'Apple地图'
						}, {
							title: '谷歌地图'
						}]
					}, (e) => {
						switch (e.index) {
							case 1:
								url =
									`http://maps.apple.com/?q=${ keyword }&ll=${ lat },${ lng }&spn=0.008766,0.019441`;
								break;
							case 2:
								url = `geo:${ lat },${ lng }?q=${ keyword }`;
								plus.runtime.openURL(url);
								break;
							default:
								break;
						}
						if (url != '') {
							plus.runtime.openURL(url, (e) => {
								plus.nativeUI.alert('本机未安装指定的地图应用');
							});
						}
					});
				}
			},
			// 导航变化时触发
			async changeNav(index = 0) {
				this.navClick = true
				let topDom = await this.query('.top-img-container')
				let navDom = await this.query('.nav-container')
				let currentDom = await this.query(domClass[index])
				this.navIndex = index
				let scrollObj = {}
				if (plus.os.name == "iOS") {
					scrollObj.duration = 0
				}
				uni.pageScrollTo({
					scrollTop: currentDom.top - topDom.top - navDom.height,
					...scrollObj,
				})
			},
			// 右上角菜单点击触发
			menuAction(item) {
				this.menuVisible = false
				if (item.key === 'report') {
					this.jumpUrl(`/pages/common/report/report?userId=${ this.dataInfo.userId }`)
				} else {
					this.shareVisible = true
				}
			},
			// 收藏改变后
			changeCollectAction() {
				this.actionAction(3, this.dataInfo).then(() => {
					this.getInfo()
				})
			},
			// 获取商家详情
			getInfo() {
				merchantInfo({
					merchantId: this.merchantId
				}).then((result) => {
					this.dataInfo = result
					this.collect = !!result.hasCollected
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.comerciante-container /deep/ .u-drawer-bottom,
	.comerciante-container /deep/ .u-mode-center-box {
		background: transparent
	}
	.comerciante-container /deep/ .uni-scroll-view>.uni-scroll-view {
		overflow: visible!important;
	}
	.comerciante-container /deep/ .uni-scroll-view>.uni-scroll-view .uni-scroll-view {
		overflow: scroll!important;
	}
	.nav-container {
		position: sticky;
		top: calc(var(--status-bar-height) + 88rpx);
		left: 0;
		z-index: 10010;
		background-color: #FFFFFF;
	}

	.top-img {
		width: 690rpx;
		height: 352rpx;
		border-radius: 20rpx;
		background-color: #f9f9f9;
	}

	.collect-btn {
		width: 114rpx;
		height: 42rpx;
		line-height: 42rpx;
		color: #FB3124;
		border: 2rpx solid #FB3124;
		border-radius: 100rpx;

		&-active {
			@extend .collect-btn;
			color: #FFFFFF;
			background-color: #FB3124;
		}
	}

	.detail-img {
		width: 122rpx;
		height: 122rpx;
		border-radius: 8rpx;
		overflow: hidden;
		background-color: #f9f9f9;
	}

	.nav-active {
		color: #FC2642;
	}

	.note-card {
		padding: 20rpx 36rpx 26rpx 30rpx;
		box-shadow: 0 4rpx 28rpx 0 rgba(0, 0, 0, 0.04);
		border-radius: 14rpx;
	}
</style>
